package cn.iocoder.an.module.business.service.auditplandetail;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.module.business.dal.dataobject.auditplanarea.AuditPlanAreaDO;
import cn.iocoder.an.module.business.dal.mysql.auditplanarea.AuditPlanAreaMapper;
import cn.iocoder.an.module.business.utils.WeComMessageUtil;
import cn.iocoder.an.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.an.module.business.controller.admin.auditplandetail.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.auditplandetail.AuditPlanDetailDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.auditplandetail.AuditPlanDetailMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 审核填报 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class AuditPlanDetailServiceImpl implements AuditPlanDetailService {

    @Resource
    private AuditPlanDetailMapper auditPlanDetailMapper;
    @Autowired
    private AuditPlanAreaMapper auditPlanAreaMapper;

    @Resource
    private AdminUserService userService;

    @Autowired
    private WeComMessageUtil weComMessageUtil;

    @Override
    public Long createAuditPlanDetail(AuditPlanDetailSaveReqVO createReqVO) {
        // 插入
        AuditPlanDetailDO auditPlanDetail = BeanUtils.toBean(createReqVO, AuditPlanDetailDO.class);
        auditPlanDetailMapper.insert(auditPlanDetail);

        // 返回
        return auditPlanDetail.getId();
    }

    @Override
    public void updateAuditPlanDetail(AuditPlanDetailSaveReqVO updateReqVO) {

        // 校验存在
        validateAuditPlanDetailExists(updateReqVO.getId());

        if (updateReqVO.getAuditStatus() != null && updateReqVO.getAuditStatus() != 1) {
            updateReqVO.setAuditTime(LocalDateTime.now());
        }

        if (updateReqVO.getCompleteStatus() != null &&  updateReqVO.getCompleteStatus() != 1) {
            sendMessage(updateReqVO.getAuditUserId());
        }

        // 更新
        AuditPlanDetailDO updateObj = BeanUtils.toBean(updateReqVO, AuditPlanDetailDO.class);
        auditPlanDetailMapper.updateById(updateObj);
    }


    public void sendMessage(List<Long> dutyUserId) {
        //推送消息
        List<AdminUserDO> userList = userService.getUserList(dutyUserId);
        String userIds = "";
        StringBuilder userIdBuilder = new StringBuilder();


        // 获取当前时间并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);

        for (AdminUserDO user : userList) {
            String userId = weComMessageUtil.getUserIdByMobile(user.getEnterpriseWeChatAccount());
            if (userId != null && !userId.trim().isEmpty()) {
                // 如果已经有内容了，先添加分隔符
                if (userIdBuilder.length() > 0) {
                    userIdBuilder.append("|");
                }
                userIdBuilder.append(userId);
            }
        }

        // 将 StringBuilder 转换为最终的字符串
        userIds = userIdBuilder.toString();
        // 可选：检查最终结果是否为空
        if (userIds.isEmpty()) {
            // 处理没有找到任何有效用户ID的情况
            System.out.printf("没有找到任何有效的企业微信 UserID");
            return;
        }

        // 1. 使用 sendTextMessage 方法 (更灵活，可以同时指定用户、部门、标签)

        String text = "您有新的审核问题追踪待审核";

        String systemMessage = text + formattedNow;
        // 将时间戳添加到消息中
        WeComMessageUtil.WeComSendResult weComSendResult = weComMessageUtil.sendTextMessage(systemMessage, userIds, null, null);
        System.out.printf("推送结果:" + weComSendResult.toString());

    }


    @Override
    public void deleteAuditPlanDetail(Long id) {
        // 校验存在
        validateAuditPlanDetailExists(id);
        // 删除
        auditPlanDetailMapper.deleteById(id);
    }

    @Override
        public void deleteAuditPlanDetailListByIds(List<Long> ids) {
        // 删除
        auditPlanDetailMapper.deleteByIds(ids);
        }


    private void validateAuditPlanDetailExists(Long id) {
        if (auditPlanDetailMapper.selectById(id) == null) {
            throw exception(AUDIT_PLAN_DETAIL_NOT_EXISTS);
        }
    }

    @Override
    public AuditPlanDetailDO getAuditPlanDetail(Long id) {
        return auditPlanDetailMapper.selectById(id);
    }

    @Override
    public PageResult<AuditPlanDetailDO> getAuditPlanDetailPage(AuditPlanDetailPageReqVO pageReqVO) {
        //查询已提交的
            LambdaQueryWrapperX<AuditPlanAreaDO> wrapper = new LambdaQueryWrapperX<>();
            wrapper.select(AuditPlanAreaDO::getId)
                    .eq(AuditPlanAreaDO::getWriteStatus, 2);
          List<Long> idList =   auditPlanAreaMapper.selectList(wrapper)
                    .stream()
                    .map(AuditPlanAreaDO::getId)
                    .collect(Collectors.toList());
        idList.add(0L);
        pageReqVO.setHasSubmit(idList);

        return auditPlanDetailMapper.selectPage(pageReqVO);
    }

}